import apiClient from './api';
import { 
  FileUploadResult, 
  ScheduleGenerationRequest, 
  ScheduleGenerationResponse,
  ScheduleData,
  Course,
  AIAnalysisResult
} from '../types/schedule';

export const scheduleService = {
  // 上传课表文件
  async uploadFile(file: File): Promise<FileUploadResult> {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await apiClient.post('/schedule/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    
    // API拦截器返回response.data，所以response就是后端返回的整个对象
    // 后端返回: { success: true, message: '...', data: {...} }
    console.log('scheduleService.uploadFile - 原始响应:', response);
    return response as unknown as FileUploadResult;
  },

  // AI生成课表
  async generateSchedule(request: ScheduleGenerationRequest): Promise<ScheduleGenerationResponse> {
    const response = await apiClient.post('/schedule/generate', request, {
      timeout: 60000, // AI分析使用60秒超时
    });
    // 由于API拦截器已经返回了response.data，所以response就是后端返回的整个对象
    console.log('scheduleService.generateSchedule - 原始响应:', response);
    return response as unknown as ScheduleGenerationResponse;
  },

  // 保存课表
  async saveSchedule(scheduleData: ScheduleData): Promise<any> {
    const response = await apiClient.post('/schedule/save', scheduleData);
    return response.data;
  },

  // 获取用户课表
  async getUserSchedule(): Promise<ScheduleData[] | null> {
    try {
      const response = await apiClient.get('/schedule/user');
      console.log('获取课表响应:', response);
      return response.data || null;
    } catch (error) {
      console.error('获取课表失败:', error);
      return null;
    }
  },

  // 更新课程信息
  async updateCourse(courseId: string, course: Course): Promise<any> {
    const response = await apiClient.put(`/schedule/course/${courseId}`, course);
    return response.data;
  },

  // 删除课程
  async deleteCourse(courseId: string): Promise<any> {
    const response = await apiClient.delete(`/schedule/course/${courseId}`);
    return response.data;
  },

  // 删除课表
  async deleteSchedule(scheduleId: string): Promise<any> {
    const response = await apiClient.delete(`/schedule/${scheduleId}`);
    return response.data;
  },

  // 重新分析课表
  async reanalyzeSchedule(fileId: string, options: any): Promise<AIAnalysisResult> {
    const response = await apiClient.post('/schedule/reanalyze', {
      fileId,
      ...options
    });
    return response.data?.data;
  }
};
